<template>
<div class="editable-cell">
  <div v-if="search" class="editable-cell-input-wrapper" >
   <!-- 多加value条件解决dia.visible不同步的问题-->
    <a-popover v-model="dia.visible&&value!=''" placement="bottom" trigger="xx" destroyTooltipOnHide>
      <template slot="content">
        <a-icon type="close" class="close" @click="hide()"/>
        <a-table size="small" rowKey="__row_number__" :row-selection="rowSelection" :columns="dia.columns[dia.dfType]"
                 :dataSource="dia.dataSource" @change="handleTableChange" :pagination="dia.pagination"
                 :customRow="selectDone" :scroll="{ y: 170 }">
          <template slot="supplier" slot-scope="text, record, index">
             <span>{{supplierDict[text]||text}}</span>
          </template>
          <template slot="choice" slot-scope="text, record, index">
            <span>{{choice(text)}}</span>
          </template>
          <template slot="matqty" slot-scope="text, record, index">
            <span :class="[{warnning:record.isWarn},{danger:record.matfax==1}]">{{text}}</span>
          </template>
          <template slot="matflag" slot-scope="text">
            <span :class="{danger:text==1}">{{text==1?'是':'否'}}</span>
          </template>
        </a-table>
      </template>
      <a-input-search ref='inputCell' size="small" :value="value" @change="handleChange" @search="fetchData" />
    </a-popover>
  </div>
  <div v-else-if="editable && inputType==='Number'" class="editable-cell-input-wrapper">
    <a-input-number ref='inputCell' size="small" :value="value" style="width:100%"  @click="click()" @change="handleInput" @keyup.enter="goNext"/>
  </div>
  <div v-else-if="subQuery && editable" class="editable-cell-input-wrapper">
    <a-input ref='inputCell' size="small" :value="value"  @change="handleInput" @keyup.enter="getSubQuery" />
  </div>
  <div v-else-if="editable" class="editable-cell-input-wrapper">
    <a-input ref='inputCell' size="small" :value="value"  @click="click()" @change="handleInput" @keyup.enter="goNext"/>
  </div>
  <div v-else class="editable-cell-text-wrapper" >
    <span>{{ value || text }} </span>
  </div>
</div>
</template>

<script>
export default {
  props: {
    text:{
      default:''
    },
    record:{
      type: Object,
      required: false
    },
    supplierDict:{
      type: Object
    },
    editable: {
      type: Boolean,
      default: false
    },
    subQuery: {
      type: Boolean,
      default: false
    },
    search: {
      type: Boolean,
      default: false
    },
    selectType: {
      type: String,
      default: 'checkbox'
    },
    inputType: {
      type: String,
      default: 'number'
    },
    dia: {
      type: Object
    }
  },
  data(){
    return {
      value: this.text,
      selectedRowKeys: [], // fetchData here to configure the default column
    };
  },
  watch:{
    text(){
      this.value = this.text
    },
    record: {
      handler(newValue, oldValue) {
        if(!newValue.__row_number__) this.value="";
        console.log("clear search value...")
      },
      deep: true
    }
  },
  mounted() {
    //监听键盘按键事件
    this.$nextTick(function () {
      let that = this;
      document.addEventListener('keyup', function (e) {
        //此处填写你的业务逻辑即可
        if (e.key === "Escape") {
           that.dia.visible=false;
        }
      })
      document.addEventListener('hide', function (e) {
        //此处填写你的业务逻辑即可
        if (e.key === "Escape") {
          that.dia.visible=false;
          console.error("hide")
        }
      })
      $(document).on("hide",function () {
        if(that.dia)that.dia.visible=false;
      });
      $(document).on("show",function () {
        if(that.dia)that.dia.visible=true;
      });
    })
  },
  computed: {
    rowSelection() {
      const that = this;
      return {
        selectedRowKeys: that.dia.selectedRowKeys,
        type: this.selectType,
        onChange: this.onSelectChange,
        hideDefaultSelections: true,
        selections: [
          {
            key: 'finish',
            text: '完成 √',
            onSelect: changableRowKeys => {
              that.$emit('change', '@submit');
            }
          }
        ],
        onSelection: this.onSelection,
      };
    },
  },
  methods: {
    debug(){
      //console.error(JSON.stringify(this.dia))
    },
    click(){
      this.$emit("click");
    },
    choice(val){
      switch(val){
        case 1:
        case '1':
          return '是';
        case 0:
        case '0':
          return '否';
        default:
          return '';
      }
    },
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      this.dia.pagination.current = pagination.current;
      this.fetchData();
    },
    selectDone(record, index) {
      let that = this;
      let done = () =>{
        choose()
        if(that.dia.dfType=='main') {
          that.$emit('change', '@submit');
        }else {
          that.$emit('change', '@choose');
        }
      }
      let choose = () =>{
        if (that.selectType == 'checkbox') {
          let res=this.dia.selectedRowKeys.findIndex((val)=>val==index+1);
          if (res == -1) {
            this.dia.selectedRowKeys.push(index + 1);
          }
        }else{
          this.dia.selectedRowKeys=[index+1];
        }
      }
      return {
        on: {
          dblclick: (e) => {
              done();
          },
          click: (e) => {
              choose();
          },
          keydown: (e) =>{
            console.error("change")
          },
          keyup: (e) => {
            console.error(e.key)
            if(e.key === "Enter" ) {
               done()
            }
          }
        }
      }
    },
    onSelection(selectedRowKeys){
      console.error('selectedRowKeys: ', selectedRowKeys);
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.dia.selectedRowKeys = selectedRowKeys;
    },
    handleChange(e) {
      this.value = e.target? e.target.value:e;
    },
    handleInput(e) {
      this.inputValidate(e);
      let oldValue = this.value;
      this.value = e.target.value;
      this.$emit('getSum', this.value);
    },
    getSubQuery(e){
         this.dia.dfType = 'sub';
         this.dia.selectedRowKeys =[];
         if(this.inputValidate(e)) this.$emit('getSubQuery', this.value)
         else this.value="";
    },
    goNext(e){
      this.$emit('done');
    },
    inputValidate(e){
      let floatReg = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/
      let numberRreg = /^\+?[1-9][0-9]*$/;
      if(this.inputType == 'number'){
        if(e.target.value&&!numberRreg.test(e.target.value)) {this.$message.error('请输入正确的数字');return false;}
      }
      if(this.inputType == 'float'){
        if(e.target.value&&!floatReg.test(e.target.value)) {this.$message.error('请输入正确的数字');return false;}
      }
      return true;
    },
    fetchData(){
      this.dia.dfType = 'main';
      this.$emit('change', this.value);
    },
    edit(){
      this.editable = true;
    },
    hide(){
      $(document).trigger("hide")
    },
    show(){
      $(document).trigger("show")
    }
  }
}

</script>

<style>
  .close {
    position: absolute;
    top: 10px;
    right: 2px;
    height: 15px;
    width: 15px;
    stroke: #00aecd;
    stroke-width: 1.25;
    cursor:pointer;
  }
  .warnning {
     color: blue;
   }
  .danger {
    color: red!important;
  }

</style>